﻿#region Licence
// <copyright file="Helpers/PrintHelper.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Threading;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using GalaSoft.MvvmLight.Ioc;
using Interfaces;

#endregion

namespace Helpers
{
    /// <summary>
    /// Permet de gérer les impressions
    /// </summary>
    public static class PrintHelper
    {
        #region fields

        private static Dictionary<PrintFormat, PrintFormatDatas> _printFormatDatas;

        #endregion

        /// <summary>
        /// Permet de créer une impression à partir d'un Stream
        /// </summary>
        /// <param name="templateStream"><see cref="Stream"/> du document en cours de constructeur</param>
        /// <param name="pageHeight">Hauteur de page</param>
        /// <param name="pageWidth">Largeur de page</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document construit</returns>
        public static FixedDocument CreateDocument(Stream templateStream, double pageWidth, double pageHeight, object datasource = null)
        {
            //Préparation du document
            FixedDocument document;
            if (templateStream != null)
            {
                var pc = new ParserContext();
                document = (FixedDocument) XamlReader.Load(templateStream, pc);
            }
            else
            {
                document = new FixedDocument();
            }

            document.DocumentPaginator.PageSize = new System.Windows.Size()
               {
                   Width = pageWidth,
                   Height = pageHeight
               };

            if (datasource != null)
            {
                InjectDocumentData(document, datasource);    
            }
            return document;
        }

        /// <summary>
        /// Permet de créer une impression à partir d'un Stream
        /// </summary>
        /// <param name="templateStream"><see cref="Stream"/> du document en cours de constructeur</param>
        /// <param name="format">Format d'impression <see cref="PrintFormat"/> voulu</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document construit</returns>
        public static FixedDocument CreateDocument(Stream templateStream, PrintFormat format, object datasource = null)
        {
            //Initialisation des types de format
            InitializePrintFormatDatas();

            var formatPrint = _printFormatDatas[format];
            return CreateDocument(templateStream, formatPrint.Width, formatPrint.Height, datasource);
        }

        /// <summary>
        /// Permet de créer une impression à partir d'un type de template
        /// </summary>
        /// <param name="template">Template du document, de type <see cref="TemplatePrint"/></param>
        /// <param name="pageHeight">Hauteur de page</param>
        /// <param name="pageWidth">Largeur de page</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document construit</returns>
        /// <remarks>
        /// TODO : Vous pouvez définir des templates XAML permettant de créer une page d'impression et l'utiliser grace à cette fonction
        /// </remarks>
        public static FixedDocument CreateDocument(TemplatePrint template, double pageWidth, double pageHeight, object datasource = null)
        {
            string uriTemplate;
            switch (template)
            {
                default:
                    uriTemplate = string.Empty;
                    break;
            }

            if (!string.IsNullOrEmpty(uriTemplate))
            {
                var info = Application.GetResourceStream(new Uri(uriTemplate));
                if (info != null)
                {
                    return CreateDocument(info.Stream, pageWidth, pageHeight, datasource);
                }
            }
            return null;
        }

        /// <summary>
        /// Permet de créer une impression à partir d'un Stream
        /// </summary>
        /// <param name="template">Template du document, de type <see cref="TemplatePrint"/></param>
        /// <param name="format">Format d'impression <see cref="PrintFormat"/> voulu</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document construit</returns>
        /// <remarks>
        /// TODO : Vous pouvez définir des templates XAML permettant de créer une page d'impression et l'utiliser grace à cette fonction
        /// </remarks>
        public static FixedDocument CreateDocument(TemplatePrint template, PrintFormat format, object datasource = null)
        {
            //Initialisation des types de format
            InitializePrintFormatDatas();

            var formatPrint = _printFormatDatas[format];
            return CreateDocument(template, formatPrint.Width, formatPrint.Height, datasource);
        }

        /// <summary>
        /// Permet de créer un document vide
        /// </summary>
        /// <param name="pageHeight">Hauteur de page</param>
        /// <param name="pageWidth">Largeur de page</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document vide construit</returns>
        public static FixedDocument CreateDocument(double pageWidth, double pageHeight, object datasource = null)
        {
            return CreateDocument(null, pageWidth, pageHeight, datasource);
        }

        /// <summary>
        /// Permet de créer une impression à partir d'un Stream
        /// </summary>
        /// <param name="format">Format d'impression <see cref="PrintFormat"/> voulu</param>
        /// <param name="datasource">DataSource du document</param>
        /// <returns>Le document construit</returns>
        public static FixedDocument CreateDocument(PrintFormat format, object datasource = null)
        {
            //Initialisation des types de format
            InitializePrintFormatDatas();

            var formatPrint = _printFormatDatas[format];
            return CreateDocument(formatPrint.Width, formatPrint.Height, datasource);
        }

        /// <summary>
        /// Ajoute une page à un document à partir d'un stream
        /// </summary>
        /// <param name="document">Document en cours</param>
        /// <param name="templatePageStream"><see cref="Stream"/>du document</param>
        /// <param name="datasource">DataSource de la page</param>
        /// <returns>Indique si l'opération s'est correctement déroulée</returns>
        public static bool AddPageToDocument(FixedDocument document, Stream templatePageStream, object datasource = null)
        {
            try
            {
                if (document != null)
                {
                    var pc = new ParserContext();
                    var page = (PageContent)XamlReader.Load(templatePageStream, pc);
                    if (datasource != null)
                    {
                        InjectPageData(page, datasource);
                    }

                    var size = document.DocumentPaginator.PageSize;

                    page.Measure(size);
                    page.Arrange(new Rect(new Point(), size));
                    page.UpdateLayout(); 

                    document.Pages.Add(page);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                SimpleIoc.Default.GetInstance<IServiceLogger>().LogFatalError(e);
                return false;
            }
        }

        /// <summary>
        /// Ajoute une page à un document à partir d'un template
        /// </summary>
        /// <param name="document">Document en cours</param>
        /// <param name="template">Template de document, de type <see cref="TemplatePrint"/></param>
        /// <param name="datasource">DataSource de la page</param>
        /// <returns>Indique si l'opération s'est correctement déroulée</returns>
        /// <remarks>
        /// TODO : Vous pouvez définir des templates XAML permettant de créer une page d'impression et l'utiliser grace à cette fonction
        /// </remarks>
        public static bool AddPageToDocument(FixedDocument document, TemplatePrint template, object datasource = null)
        {
            string uriTemplate;
            switch (template)
            {
                default:
                    uriTemplate = string.Empty;
                    break;
            }

            if (!string.IsNullOrEmpty(uriTemplate))
            {
                var info = Application.GetResourceStream(new Uri(uriTemplate));
                if (info != null)
                {
                    return AddPageToDocument(document, info.Stream, datasource);
                }
            }
            return false;
        }

        /// <summary>
        /// Convertit l'impression en document XPS
        /// </summary>
        /// <param name="outputPath">Chemin de destination du document à la sauvegarde</param>
        /// <param name="document">Document en cours</param>
        public static void SaveAsXps(string outputPath, FixedDocument document)
        {
            var fs = new FileStream(outputPath, FileMode.Create);
            ConvertFixedDocumentToXps(document, fs);
            fs.Flush();
            fs.Close();
        }

        /// <summary>
        /// Imprime le document demandé
        /// </summary>
        /// <param name="document">Document à imprimer</param>
        /// <param name="printOnMonochrome">Indique si l'on souhaite l'impression en nior et blanc</param>
        /// <param name="size">Taille du document <see cref="PageMediaSize"/></param>
        /// <param name="orientation">Orientation du document <see cref="PageOrientation"/></param>
        public static void PrintDocument(FixedDocument document, bool printOnMonochrome = false, PageMediaSizeName size = PageMediaSizeName.ISOA4, PageOrientation orientation = PageOrientation.Portrait)
        {
            var printDialog = new PrintDialog
                                  {
                                      PrintQueue = LocalPrintServer.GetDefaultPrintQueue()
                                  };

            var pt = new PrintTicket
                {
                    PageOrientation = orientation,
                    PageMediaSize = new PageMediaSize(size),
                    OutputColor = printOnMonochrome ? OutputColor.Grayscale : OutputColor.Color,
                    OutputQuality = OutputQuality.High,
                    PageResolution = new PageResolution(PageQualitativeResolution.High),
                };

            if (printDialog.ShowDialog() == true)
            {
                document.PrintTicket = pt;
                printDialog.PrintTicket = pt;
                XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
                writer.WriteAsync(document, pt);
            }
        }

        /// <summary>
        /// Permet d'enregistrer le document au format PDF
        /// </summary>
        /// <param name="document">Document à enregistrer</param>
        /// <param name="filename">Nom de fichier de destination</param>
        public static void SaveDocumentToPdf(FixedDocument document, string filename)
        {
            if (!string.IsNullOrEmpty(filename))
            {
                var memoryStream = new MemoryStream();
                var package = Package.Open(memoryStream, FileMode.Create);
                var doc = new XpsDocument(package);
                var writer = XpsDocument.CreateXpsDocumentWriter(doc);
                writer.Write(document.DocumentPaginator);

                doc.Close();
                package.Close();

                ConvertXpsToPDf(memoryStream, filename);
            }
        }

        #region private

        /// <summary>
        /// Injecte les données dans le document
        /// </summary>
        /// <param name="document"></param>
        /// <param name="dataSource"></param>
        private static void InjectDocumentData(FixedDocument document, object dataSource)
        {
            document.DataContext = dataSource;
            var dispatcher = Dispatcher.CurrentDispatcher;
            dispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);
        }

        /// <summary>
        /// Injecte les données dans la page
        /// </summary>
        /// <param name="document"></param>
        /// <param name="dataSource"></param>
        private static void InjectPageData(PageContent document, object dataSource)
        {
            document.Child.DataContext = dataSource;
            var dispatcher = Dispatcher.CurrentDispatcher;
            dispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);
        }

        /// <summary>
        /// Convert a FixedDocument to an XPS file.
        /// </summary>
        /// <param name="fixedDoc">The FixedDocument to convert.</param>
        /// <param name="outputStream">The output stream.</param>
        private static void ConvertFixedDocumentToXps(FixedDocument fixedDoc, Stream outputStream)
        {
            var package = Package.Open(outputStream, FileMode.Create);
            var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed);
            XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);

            // xps documents are built using fixed document sequences
            var fixedDocSeq = new FixedDocumentSequence();
            var docRef = new DocumentReference();
            docRef.BeginInit();
            docRef.SetDocument(fixedDoc);
            docRef.EndInit();
            ((IAddChild)fixedDocSeq).AddChild(docRef);

            // write out our fixed document to xps
            xpsWriter.Write(fixedDocSeq.DocumentPaginator);

            xpsDoc.Close();
            package.Close();
        }

        /// <summary>
        /// Initialisation des formats d'impression
        /// </summary>
        private static void InitializePrintFormatDatas()
        {
            _printFormatDatas = new Dictionary<PrintFormat, PrintFormatDatas>
            {
                {PrintFormat.A4, new PrintFormatDatas {Width = 561, Height = 792}},
                {PrintFormat.A4Landscape, new PrintFormatDatas {Width = 792, Height = 561}},
                {PrintFormat.A3, new PrintFormatDatas {Width = 1122, Height = 1584}},
                {PrintFormat.A3Landscape, new PrintFormatDatas {Width = 1584, Height = 1122}}
            };
        }

        /// <summary>
        /// Permet de convertir un document XPS en PDF
        /// </summary>
        /// <param name="document"></param>
        /// <param name="filename"></param>
        private static void ConvertXpsToPDf(Stream document, string filename)
        {
            var doc = PdfSharp.Xps.XpsModel.XpsDocument.Open(document);
            PdfSharp.Xps.XpsConverter.Convert(doc, filename, 0);
        }
	    #endregion
    }

    /// <summary>
    /// Perrmet de lister les différents types de template de l'application
    /// </summary>
    /// <remarks>
    /// TODO : Ajouter ici les templates de page que vous ajoutez à l'application
    /// </remarks>
    public enum TemplatePrint
    {}

    /// <summary>
    /// Enumération des formats d'impression
    /// </summary>
    public enum PrintFormat
    {
        A4,
        A4Landscape,
        A3,
        A3Landscape
    }

    /// <summary>
    /// Données sur les tailles des impressions
    /// </summary>
    public struct PrintFormatDatas
    {
        public double Width { get; set; }
        public double Height { get; set; }
    }
}
